package packutil.idgen;

import java.io.File;
import packutil.FileUtil;

public class FileSavedIdGenerator implements IIdGenerator {

	private final String lastIdFile;
	
	private Integer lastId = null;

	public FileSavedIdGenerator(String lastIdFile) {
		this.lastIdFile = lastIdFile;
	}

	@Override
	public int nextIdAsInt() {

		if(lastId != null) {
			return ++lastId;
		}
		
		int nextId;
		if (!new File(lastIdFile).exists()) {
			nextId = 0;
		} else {
			nextId = Integer.parseInt(FileUtil.readStringFromFile(lastIdFile)) + 1;
		}

		FileUtil.writeToFile(lastIdFile, nextId + "");

		lastId = nextId;
		return nextId;
	}

}
